$(function() {

    function initTab(pageNum, pageSize) {
        pageNum = pageNum && pageNum > 0 ? pageNum : getCurPage();
        pageNum = pageNum > 0 ? pageNum : 1;
        pageSize = pageSize > 0 ? pageSize : 10;
        var param = {
            'pageSize': pageSize,
            'pageNum': pageNum
        }
        var visibleRange = $("#typeDropdown").attr('val');
        var url = '/doc/page';
        if (-1 != visibleRange) {
            var searchMap = new Object();
            searchMap['visibleRange'] = visibleRange;
            if (visibleRange == 2) {
                url = '/doc/pageByProject';
                searchMap['projectIds'] = $("#projects").val();
            }
            param['searchMap'] = searchMap;
        }
        $.get(url, param, function(data) {
            if (data && data.retCode == 0) {
                renderedTable(data.retVal);
            }
        });
    }

    // 分页
    function pageInit(current, pages) {
        var options = {
            bootstrapMajorVersion: 3,
            currentPage: current > 0 ? current : 1,
            totalPages: pages > 0 ? pages : 1,
            numberOfPages: 5,
            itemTexts: function(type, page, current) { //文字翻译
                switch (type) {
                    case "first":
                        return "首页";
                    case "prev":
                        return "上一页";
                    case "next":
                        return "下一页";
                    case "last":
                        return "尾页";
                    case "page":
                        return page;
                }
            },
            pageUrl: '#',
            onPageClicked: function(event, originalEvent, type, page) {
                initTab(page);
            }
        };
        $(".pagination").bootstrapPaginator(options);
    }

    function getCurPage() {
        try {
            var page = $(".pagination").bootstrapPaginator('getPages');
            return page ? page : 1;
        } catch (e) {
            return 1;
        }
    }


    // 单个删除数据
    $('#proTable').on('click', 'tbody a[name="del"]', function(e) {
        var self = $(this);
        $.get('/doc/delete/' + self.attr('docId'), function(data) {
            if (data && data.retCode == 0) {
                self.parents("tr").remove();
            }
        });
    });

    // 批量选择
    $("#selectBatch").click(function(event) {
        if (this.checked) {
            $("#proTable>tbody :checkbox").each(function() {
                if (!this.disabled) {
                    this.checked = true;
                }
            });
        } else {
            $("#proTable>tbody :checkbox").each(function() {
                this.checked = false;
            });
        }
    });

    $('#proTable').on('click', 'tbody :checkbox', function(e) {
        if (!this.checked) {
            $("#selectBatch").get(0).checked = false;
        } else {
            var flag = false;
            $("#proTable>tbody :checkbox").each(function() {
                if (!this.checked) {
                    flag = true;
                    return;
                }
            });
            if (flag) {
                $("#selectBatch").get(0).checked = false;
            } else {
                $("#selectBatch").get(0).checked = true;
            }
        }
    });

    //批量删除
    $("#btnDelBatch").click(function(event) {
        var ids = new Array();
        $("#proTable>tbody :checked").each(function() {
            if (this.checked) {
                ids.push(this.getAttribute("docId"));
            }
        });
        if (ids.length > 0) {
            // jquey传递数组到后台，需要用“ids[]”获取，因此此处写成，ids[]
            $.post('/doc/delete/batch', { 'ids[]': ids }, function(data, textStatus, xhr) {
                /*optional stuff to do after success */
                if (data && data.retCode == 0) {
                    $("#proTable>tbody :checked").parents("tr").remove();
                }
            });
        }
    });

    // 发布版本
    $("body").on('click', "a[name='release']", function(event) {
        // 点击发布时，补充发布弹框数据。
        var self = $(this);
        var vrForm = $("#rvForm");
        vrForm.find("#rvDocId").val(self.attr("docId"));
        vrForm.find("#rvDocName").text(self.attr("docName"));
        var lastRealse = self.attr("lastRealse");
        if (lastRealse) {
            $("#lastRealse").text(lastRealse);
        } else {
            $("#lastRealse").html('<span style="color: #968C8CE6;">尚未发布</span>');
        }
    });

    /**
     * 发布版本
     */
    $("body").on('click', "#releaseBtn", function(event) {
        // 点击发布时，补充发布弹框数据。
        var self = $(this);
        var docId = $.trim($("#rvDocId").val());
        var verNo = $.trim($("#rvVerNo").val());
        var desc = $.trim($("#rvDesc").val());
        if (docId != undefined && docId != '' && verNo != undefined && verNo != '') {
            $.post('/docRelease/versionRelease', { docId: docId, versionNo: verNo, description: desc }, function(data, textStatus, xhr) {
                if (data && data.retCode == 0) {
                    // 发布成功
                    // 关闭窗口，清空数据
                    $('#release-modal').modal('hide');
                    $('#rvForm :reset').click();
                    var parObj = $("#proTable tr[docId='" + docId + "']");
                    var aRel = "<a target='_blank' href='/static/html/doc/release.html?docId=" + docId + "&verNo=" + verNo + "'>" + verNo + "</a>"
                    parObj.find("td[name='latestVersion']").empty().html(aRel);
                    parObj.find("a[name='release']").attr("lastRealse", verNo);
                } else {
                    // TODO 发布失败
                }
            });
        }
    });

    var projectBH = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        //预加载数据
        prefetch: {
            url: '/project/page?searchMap[name]=%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var projects = new Array();
                    if (data.retVal.list) {
                        data.retVal.list.forEach(function(obj) {
                            projects.push({
                                'id': obj.id,
                                'name': obj.name
                            });
                        });
                    }
                    return projects;
                }
            }
        },
        remote: {
            url: '/project/page?searchMap[name]=%QUERY',
            wildcard: '%QUERY',
            filter: function(data) {
                if (data && data.retCode == 0) {
                    var projects = new Array();
                    if (data.retVal.list) {
                        data.retVal.list.forEach(function(obj) {
                            projects.push({
                                'id': obj.id,
                                'name': obj.name
                            });
                        });
                    }
                    return projects;
                }
            }
        }
    });

    projectBH.initialize();

    // 项目选择控件
    $("#projects").tagsinput({
        tagClass: function(item) {
            return (item.length > 10 ? 'big' : 'small') + ' label label-warning sel-tagsinput';
        },
        itemValue: 'id',
        itemText: 'name',
        autoSelect: true,
        typeaheadjs: {
            classNames: { input: 'Typeahead-input' },
            name: 'projects',
            value: 'id',
            display: 'name',
            source: projectBH.ttAdapter()
        }
    });

    $("#projects").on('itemAdded itemRemoved', function() {
        initTab(1, 10);
    });

    $("#typeSel").on('click', 'a', function() {
        var self = $(this);
        var type = self.attr("val");
        var btn = $("#typeDropdown");
        if (btn.attr('val') != type) {
            if (2 == type) {
                $('#projectSpan').show();
            } else {
                $('#projectSpan').hide();
            }
            btn.attr('val', type)
                .text(self.text())
                .append('&nbsp;<span class="caret"></span>');
            initTab(1, 10);
        };
    });

    /**
     * 渲染表格数据
     *
     * @param      {string}  page    The page
     */
    function renderedTable(page) {
        $('#proTable>tbody').empty();
        $("#selectBatch").get(0).checked = false;
        if (page == null || page.list == null) {
            $('#proTable>tbody').append('');
            pageInit(1, 0);
            return;
        }
        var proList = page.list;
        var html = '';
        var docInfo;
        var user = sessionStorage.getItem("account");
        for (var i = 0; i < proList.length; i++) {
            docInfo = proList[i];
            if (null == docInfo) {
                continue;
            }
            html += '<tr docId="' + docInfo.id + '" class="row">';
            html += '<td>';
            if (user == docInfo.creator) {
                html += '<input type="checkbox" docId="' + docInfo.id + '" />';
            } else {
                html += '<input type="checkbox" disabled />';
            }
            html += '</td>';
            html += '<td> <a target="_blank" href="/static/html/doc/show.html?' + docInfo.id + '" >' + docInfo.name + '</a></td>';
            html += '<td>';
            if (docInfo.tag) {
                docInfo.tag.split(',').forEach(function(e) {
                    html += '<span class="label label-success">' + e + '</span>';
                });
            }
            html += '</td>';
            html += '<td>' + (docInfo.description != null ? docInfo.description : '') + '</td>';
            html += '<td name="latestVersion">' + (docInfo.latestVersion != null ? "<a target='_blank' href='/static/html/doc/release.html?docId=" + docInfo.id + "&verNo=" + docInfo.latestVersion + "'>" + docInfo.latestVersion + "</a>" : '<span style="color: #968C8CE6;">尚未发布</span>') + '</td>';
            html += '<td>' + conv_time(docInfo.createTime, false) + '</td>';
            html += '<td>' + conv_time(docInfo.updateTime, false) + '</td>';
            html += '<td>' + '<span class="badge badge-info badge-blue">' + docInfo.creator + '</span>' + '</td>';
            html += '<td>';
            if (docInfo.projects) {
                docInfo.projects.forEach(function(e, index) {
                    html += '&nbsp;<span class="label label-warning">' + e.name + '</span>';
                });
            }
            html += '</td>';
            html += '<td class="text-center" nowrap="nowrap">';
            html += '<a target="_blank" href="/static/html/doc/show.html?' + docInfo.id + '" >详情</a>'
            if (user == docInfo.creator) {
                html += '&nbsp;|&nbsp;<a name="upd" docId="' + docInfo.id +
                    '" href="/static/html/doc/update.html?' + docInfo.id + '">编辑</a>' +
                    '&nbsp;|&nbsp;<a name="release" href="#" data-toggle="modal" data-target="#release-modal" docId="' +
                    docInfo.id +
                    '" docName="' + docInfo.name +
                    '" lastRealse="' + (docInfo.latestVersion != null ? docInfo.latestVersion : '') +
                    '">发布</a>' +
                    '&nbsp;|&nbsp;<a name="del" href="#" onclick="deletePro(event);" docId="' +
                    docInfo.id +
                    '" class="">删除</a>';
            }
            html += '</td>';
            html += '</tr>';
        }
        $('#proTable>tbody').append(html);
        pageInit(page.pageNum, page.pages);
    }

    function init() {
        // 解析地址栏
        var id = getQueryString('projectId');
        var name = getQueryString('projectName');
        if (stringIsNotNull(id) && stringIsNotNull(name)) {
            var pro = $('#typeSel a[val=2]');
            $("#typeDropdown").attr('val', pro.attr('val')).text(pro.text()).append('&nbsp;<span class="caret"></span>');
            $('#projectSpan').show();
            $('#projects').tagsinput('add', { 'id': id, 'name': name });
        } else {
            initTab(1, 10);
        }
    }

    init();

});